let path = require('path');
let multer = require('multer');
let express = require('express');
let apiAddr = require('../config/PublicPath');
let {v4} = require('uuid');
let uploadImgFileApp = express();

// 下面开始创建文件存储的配置

let storage = multer.diskStorage({
    destination: function (req, file, cb){
        if (file.mimetype.includes('image')){ // 如果上传的文件包含image，就统一放到上级目录的storage里面的images里面
            cb(null, path.join(__dirname, '../storage/images'))
        }
    },
    filename: function (req, file, cb){ // 需要保证文件名不能重复，因为重复就会覆盖，使用uuid的v4拼接
        cb(null, v4()+file.originalname)
    }
})

let uploadParams = multer({
    storage
})

let uploadConfig = uploadParams.fields([
    {
        name: 'blogIllustrations',
        maxCount: 9 // 一次最多同时上传九个
    }
]);

uploadImgFileApp.post('/', uploadConfig, function (req, res){
    console.log(req.files.blogIllustrations);
    // console.log('上传数据的长度',req.files.blogIllustrations.length);
    // console.log('上传数据的类型',typeof req.files.blogIllustrations);
    let resData = [];
    for (let i = 0, len = req.files.blogIllustrations.length; i < len; i++){
        resData.push(`${apiAddr.hostAddr}${apiAddr.getImgApiAddr}/${req.files.blogIllustrations[i].filename}`)
    }

    res.setHeader('Content-Type','application/json;charset=utf-8');
    res.send({ // 返回状态码 信息 响应数据
        status: 200,
        message: '上传成功',
        data: {
            imgList: resData
        }
    })

})

module.exports = {
    uploadImgFileApp
}